package com.kingmed.kmss.bpmn.flow.utils;

import java.util.List;

import com.kingmed.kmss.common.constant.marketing.MktConstants;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationDTO;
import com.kingmed.kmss.common.enums.admin.OrgLevel;
import com.kingmed.kmss.common.utils.AppContextUtil;
import com.kingmed.kmss.common.utils.StringUtils;
import com.kingmed.kmss.framework.feign.client.admin.CommonAdminFeignServiceFacade;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OrgUtils {

	static
	CommonAdminFeignServiceFacade remoteAdminSvc = AppContextUtil.getBean(CommonAdminFeignServiceFacade.class);

	// 根据username获取上级部门，取orgFullName
	public static  String getDeptByUser(String userName) {
		if (StringUtils.isEmpty(userName)) {
			return "";
		}
		Long userId = remoteAdminSvc.getUserIdByName(userName);
		
		Integer manageDeptType = remoteAdminSvc.getManageOrgType(userName);
		List<OrganizationDTO> orgs = remoteAdminSvc.getParentUpByUserId(userId);
		
		String orgFullName = null;
		//如果是子公司，只需要到子公司，不需要大区和集团
		if (manageDeptType == OrgLevel.BRANCH.getCode()) {
			for(int i=0;i<orgs.size();++i) {
				if (orgs.get(i).getLevel() == OrgLevel.BRANCH.getCode()) {
					orgFullName = String.format("%s%s%s", orgs.get(i).getOrgName(), 
							i>0? MktConstants.LIST_STRING_SEPERATOR_MIDDLE_LINE:"",
									i>0?orgs.get(i-1).getOrgName():"");
					break;
				}
				
			}
		}//其他情况，按正常的上级拼接
		else {
			StringBuffer buff = new StringBuffer();
			for(int i = orgs.size()-2; i>=0; --i) {
				if (i<0) {
					break;
				}
				buff.append(orgs.get(i).getOrgName());
				if (i != 0) {
					buff.append(MktConstants.LIST_STRING_SEPERATOR_MIDDLE_LINE);
				}
			}
			orgFullName = buff.toString();
		}

		//这里原本想处理集团根节点，或者是没有部门的情况
		if (StringUtils.isEmpty(orgFullName) || manageDeptType == null) {
			if (CollUtil.isNotEmpty(orgs)) {
				orgFullName = orgs.get(0).getOrgName();
			}
		}
		log.debug("OrgUtils::getDeptByUser(): {} -> {} -> {}", userName, userId, orgFullName);
		return orgFullName;
	}
}
